from sqlalchemy.ext.asyncio import AsyncSession as Session
from app.schemas.waveup.trading_pair import (
    WPTradingPairListQueryReq, 
    WPTradingPairCreate,
    WPTradingPairUpdate
)
from app.models.waveup.trading_pair import TradingPair
from sqlalchemy import select

async def get_trading_pair_list(session: Session, query: WPTradingPairListQueryReq):
    """查询WaveUp交易对列表"""
    statement = select(TradingPair)
    if query.tradeStatusList:
        statement = statement.where(TradingPair.tradeStatus.in_(query.tradeStatusList))
    
    # 计算总数
    total = await session.execute(statement)
    total = len(total.scalars().all())

    # 分页查询
    statement = statement.offset((query.pageNo - 1) * query.pageSize).limit(query.pageSize)
    result = await session.execute(statement)

    return {
        "records": result.scalars().all(),
        "total": total,
        "pageNo": query.pageNo,
        "pageSize": query.pageSize
    }

async def create_trading_pair(
    session: Session, 
    trading_pair_in: WPTradingPairCreate
) -> TradingPair:
    """创建新交易对"""
    db_trading_pair = TradingPair.model_validate(trading_pair_in)
    session.add(db_trading_pair)
    await session.commit()
    await session.refresh(db_trading_pair)
    return db_trading_pair

async def get_by_product_pair_id(
    session: Session, product_pair_id: int
) -> TradingPair | None:
    """根据交易对ID查询交易对"""
    statement = select(TradingPair).where(TradingPair.productPairId == product_pair_id)
    result = await session.execute(statement)
    return result.scalars().first()

async def get_trading_pair_by_id(
    session: Session, id: int
) -> TradingPair | None:
    """根据ID查询交易对"""
    statement = select(TradingPair).where(TradingPair.id == id)
    result = await session.execute(statement)
    return result.scalars().first()

async def update_trading_pair(
    session: Session, trading_pair_update: WPTradingPairUpdate
) -> TradingPair | None:
    """更新交易对"""
    db_trading_pair = await get_trading_pair_by_id(
        session, trading_pair_update.id
    )
    if not db_trading_pair:
        return None
    db_trading_pair.model_validate(trading_pair_update)
    await session.commit()
    await session.refresh(db_trading_pair)
    return db_trading_pair